package com.wu.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextFactory
  implements ApplicationContextAware
{
  private static transient ApplicationContext SPRING_CONTEXT;

  public void setApplicationContext(ApplicationContext applicationContext)
    throws BeansException
  {
    SPRING_CONTEXT = applicationContext;
  }

  public static ApplicationContext getSpringContext() {
    return SPRING_CONTEXT;
  }

  public static <T> T getBean(Class<T> type, String name)
  {
    if (getSpringContext().containsBean(name)) {
      Object bean = getSpringContext().getBean(name);
      if (type.isInstance(bean)) {
        return (T) bean;
      }
    }
    return null;
  }

  public static <T> T getBean(Class<T> clazz) {
    return clazz.cast(BeanFactoryUtils.beanOfTypeIncludingAncestors(SPRING_CONTEXT, clazz));
  }
}
